package com.gla.giliair.web.customer;

import com.gla.giliair.entity.MOrder;
import com.gla.giliair.util.EmailUtil;
import com.gla.giliair.util.IndentityUtil;
import com.gla.giliair.util.MapGenerator;
import com.gla.giliair.util.PatternUtil;
import com.gla.giliair.web.BaseController;
import com.gla.giliair.web.vo.CustomerVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: Yingtian qian
 * @Date: 2021/8/24 18:48
 */
@Api(tags = "订单模块")
@RestController
@RequestMapping("/api/user")
public class OrderController extends BaseController {
    @ApiOperation(value = "获取订单列表", notes = "根据单个或多个状态码，获取订单列表；或者直接获取订单列表", produces = "application/json")
    @GetMapping("/orderList")
    @ResponseBody
    public Map<String, Object> findOrderList(//订单状态默认值为空，表示查询全部订单；其他值表示查询相应状态的订单，可传多个状态码进行合并查询；无效状态码会被忽略
                                             //状态码：0->待付款；1->已付款，未选座；2->已选座；3->已出票；-1->用户取消；-2->用户退票；-3->管理员关闭；-4->超时取消；-5->用户申请退票
                                             @RequestParam(value = "state", required = false) Integer[] states,
                                             @RequestParam(value = "page", defaultValue = "1") Integer page,
                                             @RequestParam(value = "pageSize", defaultValue = "16") Integer pageSize,
                                             HttpSession httpSession) {
        List<Integer> stateList = null;
        if (states != null) {
            stateList = new ArrayList<>();
            for (Integer state : states) {
                if (state == 0 || state == 1 || state == 2 || state == 3 || state == -1 || state == -2 || state == -3 || state == -4 || state == -5) {
                    stateList.add(state);
                }
            }
        }
        CustomerVO userTemp = (CustomerVO) httpSession.getAttribute("user");
        return orderService.findOrdersByCustomerIdAndStates(userTemp.getCustomerId(), stateList, page, pageSize);
    }

    @ApiOperation(value = "生成订单", notes = "填写订票信息，生成订单；5分钟内不支付会自动取消订单", produces = "application/json")
    @PostMapping("/createOrder")
    @ResponseBody
    public Map<String, Object> createOrder(@RequestParam("flightId") Long flightId,
                                           @RequestParam("seatType") Integer seatType,
                                           @RequestParam("IDNumber") String IDNumber,
                                           @RequestParam("realname") String realname,
                                           @RequestParam("phone") String phone,
                                           @RequestParam("contacts") String contacts,
                                           @RequestParam("contactsPhone") String contactsPhone,
                                           HttpSession httpSession) {
        if (flightId == null) {
            return MapGenerator.getRes(500, "请输入航班id！");
        }
        if (!StringUtils.hasText(IDNumber)) {
            return MapGenerator.getRes(501, "请输入乘机人身份证号！");
        }
        if (!StringUtils.hasText(realname)) {
            return MapGenerator.getRes(502, "请输入乘机人真实姓名！");
        }
        if (!StringUtils.hasText(phone)) {
            return MapGenerator.getRes(503, "请输入乘机人电话！");
        }
        if (!StringUtils.hasText(contacts)) {
            return MapGenerator.getRes(504, "请输入联系人真实姓名！");
        }
        if (!StringUtils.hasText(contactsPhone)) {
            return MapGenerator.getRes(505, "请输入联系人电话！");
        }
        if (!PatternUtil.isPhone(phone)) {
            return MapGenerator.getRes(506, "乘机人电话格式有误！");
        }
        if (!PatternUtil.isPhone(contactsPhone)) {
            return MapGenerator.getRes(507, "联系人电话格式有误！");
        }
        if (!PatternUtil.isIdentity(IDNumber)) {
            return MapGenerator.getRes(508, "乘机人身份证号格式有误！");
        }
        if (seatType != 0 && seatType != 1 && seatType != 2) {
            return MapGenerator.getRes(509, "座位类型不存在！");
        }
        try {
            if (!IndentityUtil.idCheck(IDNumber, realname)) {
                return MapGenerator.getRes(510, "乘机人身份证号不存在，或与真实姓名不匹配！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        CustomerVO userTemp = (CustomerVO) httpSession.getAttribute("user");

        MOrder mOrder = new MOrder();
        mOrder.setFlightId(flightId);
        mOrder.setIdNumber(IDNumber);
        mOrder.setRealname(realname);
        mOrder.setPhone(phone);
        mOrder.setContacts(contacts);
        mOrder.setContactsPhone(contactsPhone);
        mOrder.setSeatType(seatType);
        mOrder.setCustomerId(userTemp.getCustomerId());
        mOrder.setDiscountType2(userTemp.getCustomerType());

        Map<String, Object> res = orderService.createOrder(mOrder);
        if ((Integer) res.get("status") == 200) {
            MOrder mOrderParam = (MOrder) res.get("data");

            Integer delayTime = 5;
            delayService.cancelOrderAfter(delayTime, mOrderParam);

            String email = userTemp.getEmail();
            if (StringUtils.hasText(email)) {

                String msg = "亲爱的客户" + userTemp.getNickname() + "，您的" +
                        mOrderParam.getLeavePoint() + "-" + mOrderParam.getArrivePoint() +
                        "航班订单已下单成功，余位有限，请在" + delayTime + "分钟内支付，逾时将自动取消订单！";
                EmailUtil.sendEmail(msg, "下单成功", email);
            }
        }
        return res;
    }

    @ApiOperation(value = "取消订单", notes = "取消订单", produces = "application/json")
    @PostMapping("/cancelOrder")
    @ResponseBody
    public Map<String, Object> cancelOrder(@RequestParam("orderId") Long orderId,
                                           HttpSession httpSession) {
        CustomerVO userTemp = (CustomerVO) httpSession.getAttribute("user");

        MOrder mOrder = new MOrder();
        mOrder.setCustomerId(userTemp.getCustomerId());
        mOrder.setOrderId(orderId);

        return orderService.cancelOrder(mOrder);
    }
}
